package com.cyc.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/login.html")
    public String login(@RequestParam("redirect_url") String url,Model model,@CookieValue(value = "sso_token",required = false) String sso_token){
        if (!StringUtils.isEmpty(sso_token)){
            return "redirect:"+url+"?token="+sso_token;
        }

        model.addAttribute("url",url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(String username, String password, String url, HttpServletResponse response){

        String uuid = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(uuid,username);

        Cookie cookie = new Cookie("sso_token", uuid);
        response.addCookie(cookie);

        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            return "redirect:"+url+"?token="+uuid;
        }else {
            return "login";
        }


    }




}
